import Data.List 
import System.IO

parseInput :: String -> [Int]
parseInput = map read . lines 

findTwoSum :: Int -> [Int] -> Maybe (Int, Int)
findTwoSum _ []  = Nothing
findTwoSum _ [x] = Nothing
findTwoSum target (x:xs) = 
    if reminderExits 
        then Just (x,reminder)
        else findTwoSum target xs
    where
        reminder = target - x
        reminderExits = elem reminder xs

findThreeSum2020 :: [Int] -> Maybe (Int, Int, Int) 
findThreeSum2020 []  = Nothing
findThreeSum2020 [x] = Nothing
findThreeSum2020 (x:xs) = 
    case twoSumReminder of 
        Just (y,z) -> Just (x,y,z)
        Nothing -> findThreeSum2020 xs
    where
        reminder = 2020 - x
        twoSumReminder = findTwoSum reminder xs

outputValue :: Maybe (Int, Int, Int) -> Int
outputValue result = 
    case result of 
        Just (x, y, z) -> x * y * z
        Nothing -> 0

main :: IO ()
main = do
    input <- readFile "./day01/input.txt"
    print . outputValue . findThreeSum2020 . parseInput $ input